import axios from 'axios'
import useLoginStore from '@/store/user/index.js'
import Qs from "qs";


// let host = window.location.protocol + "//" + window.location.host;
let base = process.env.NODE_ENV == 'development' ? '/platform' : "http://47.117.36.70/platform";
const request = axios.create({
  baseURL: base,
  timeout: 100000,
  paramsSerializer(params) {
    return Qs.stringify(params, { arrayFormat: 'repeat', allowDots: true });
  }
})
request.interceptors.request.use((config) => {
  console.log('request', request);
  //设置请求token
  const loginStore = useLoginStore()
  const loginInfo = JSON.parse(localStorage.getItem('loginInfo'))

  if (loginInfo) {
    config.headers.token = `${loginInfo.token}`
  }
  if (config.method === "get") {
    //如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
    // config.paramsSerializer = (params) =>{
    //   console.log('params====',params);
    //    const aa = qs.stringify(params, {
    //     arrayFormat: "repeat",
    //   });
    //   console.log('aa',aa);
    //   return aa
    // };
    // config.paramsSerializer = jj => {
    //   return Qs.stringify(jj, { arrayFormat: 'indices' })
    // }
    config.paramsSerializer.serialize = (params) => {
      return Qs.stringify(params, { arrayFormat: 'repeat', allowDots: true });
    }
    // config = {...config, paramsSerializer(params) {
    //   return Qs.stringify(params, { arrayFormat: 'repeat', allowDots: true });
    // }}
  }
  return config
})

request.interceptors.response.use(
  (success) => {
    // 如果后端开放了content-disposition，就同时把header也返回
    if (success.headers["content-disposition"]) {
      return success
    }
    // if (success.data.code === 401) {
    //   useLoginStore().token = ""
    //   setLocalStore(TOKEN,"")
    //   // router.push("/login")
    // }
    // console.log(success, '--------------------')
    if (success.data.code == 401) {
      localStorage.removeItem('loginInfo')
      window.location.replace("/login");
    }
    return success.data
  },
  (err) => {
    return Promise.reject(new Error(err.message))
  }
)

export default request
